import {Component, OnInit, TemplateRef, ViewChild} from '@angular/core';
import {TableGen, SelectorGen, BtnsGen, PredefineForProjectService} from '@list-page';
import {FileManagerService} from './file-manager.service';
import {NzMessageService} from 'ng-zorro-antd';

@Component({
    selector: 'kylin-file-manager',
    templateUrl: './file-manager.component.html',
    styleUrls: ['./file-manager.component.less']
})
export class FileManagerComponent implements OnInit {

    selectorGen: SelectorGen;
    btnsGen: BtnsGen;
    tableGen: TableGen;
    queryReqInfo: any;

    @ViewChild('contentTemp') contentTemp: TemplateRef<void>;
    @ViewChild('operationTemp') operationTemp: TemplateRef<void>;

    constructor(private predefineSvc: PredefineForProjectService, private fileMngSvc: FileManagerService, private message: NzMessageService) {
    }

    ngOnInit() {
        this.initListPageInfo();
    }

    initListPageInfo() {
        this.createSelectorGen();
        this.createBtnsGen();
        this.createTableGen();
        this.createQueryInfo();
    }

    createSelectorGen() {
        this.selectorGen = {
            selectorArr: [
                {
                    label: '项目名称',
                    key: 'applicationName',
                    type: 'dropdown',
                    dataSource: this.fileMngSvc.getProjectNameOptions()
                },
                {
                    label: '文件类型', key: 'contentType',
                    type: 'dropdown',
                    dataSource: this.fileMngSvc.getContentTypeOptions()
                },
                {
                    label: '文件名称',
                    key: 'name',
                    type: 'text'
                },
            ],
            btnPosition: 'topRight',
            splitScale: 3,
            isCollapse: false,
            classCover: 'cover1'
        };
    };

    createBtnsGen() {
        this.btnsGen = { // 批量导出/批量删除
            right: [
                this.predefineSvc.getExport({
                    reqInfo: {
                        path: '/files/download',
                        method: 'get',
                        params: {}
                    },
                    idProp: 'url',
                    reqProp: 'urls',
                    operation: '批量下载'
                }),
                this.predefineSvc.getBatchedDelete({
                    title: '确认删除所选文件(删除后不可恢复)？',
                    reqInfo: {
                        path: '/files',
                        method: 'delete',
                        params: {}
                    },
                    idProp: 'id',
                    reqProp: 'ids'
                }),
            ]
        };
    };

    createTableGen() {
        this.tableGen = {
            cols: [
                {head: '所属项目', prop: 'applicationName'},
                {head: '文件名称', prop: 'name'},
                {head: '文件类型', prop: 'contentType'},
                {head: '文件大小', prop: 'size', sort: ''},
                {head: '内容', prop: 'contentTemp', type: 'template'},
                {head: '创建人', prop: 'createUser'},
                {head: '创建时间', prop: 'createTime', sort: '', type: 'date'},
                {head: '操作', prop: 'operationTemp', type: 'template'},
            ],
            // localData: this.fileMngSvc.getLocalData(),
            dataProcess: (data, funSet) => {
                data.map(item => {
                    item.contentTemp = this.contentTemp;
                    item.urlTranslate = this.genContentImgUrl(item.contentType, item.url);
                    item.isImg = this.imgCheck(item.url);
                    item.operationTemp = this.operationTemp;
                });
                return data;
            }
        };
    };

    createQueryInfo() {
        this.queryReqInfo = {
            path: '/files',
            method: 'GET',
            params: {}
        };
    };

    genContentImgUrl(contentType: string, url: string): string {
        if (contentType === 'image') {
            return this.fileMngSvc.getImgHost() + url;
        } else {
            return this.fileMngSvc.getDefaultImgByType(contentType);
        }
    }

    imgCheck(url: string): boolean {
        const RegRst = url.match(/^.+\.(\w+)$/);
        const extensionName = RegRst ? RegRst[1] : '';
        return !!/.(gif|jpg|jpeg|png|gif|jpg|png)$/.test(extensionName);
    }

    deleteFile(data, funSet) {
        this.fileMngSvc.delete(data.id).then(rep => {
            if (rep.resp_code) {
                this.message.success(`文件 ${data.name} 删除成功`);
                funSet.refreshList();
            } else {
                this.message.error(`文件 ${data.name} 删除失败，` + rep.resp_msg);
            }
        });
    }

    downloadFile(data) {
        this.fileMngSvc.download(data.url);
    }
}
